package core

import java.awt.image.BufferedImage
import Utils.RGB
import java.io.File


class EnergyGetter(img: BufferedImage) extends App {
  //adapted from http://stackoverflow.com/questions/2381908/how-to-create-and-use-a-multi-dimensional-array-in-scala-2-8
  /**
   * creates energy map from buffered image
   * 
   * @param img		the bufferedimage
   * @return 		the energy map
   */
  def getEnergyMap() : EnergyMap = {
    val toReturn = Array.ofDim[Double](img.getHeight, img.getWidth)
    val imgheight = img.getHeight
    val imgwidth = img.getWidth
    
    for (x <- 0 to (imgwidth - 1); y <- 0 to (imgheight - 1)) {
      val rgbVal = new RGB(img.getRGB(x, y))

      //crazy cool mapping http://speaking-my-language.blogspot.com/2009/09/3-things-you-didnt-know-scala-pattern.html
      val (sum, tot) = 
        //all possible neighbor pixels
        List((x-1, y-1), (x, y-1), (x+1, y-1), (x-1, y), (x+1, y+1), (x-1, y+1), (x, y+1), (x+1, y+1)).
           foldLeft((0.0, 0)) {
	        case ((prevTot, prevNum), (thisX, thisY)) =>
	          //make sure it is in bounds
	          if (thisX < 0 || thisX >= imgwidth || 
	              thisY < 0 || thisY >= imgheight) {
	            (prevTot, prevNum)
	          }
	          else {
	            //calculate difference from this pixel and current pixel
	            val curRGB = new RGB(img.getRGB(thisX, thisY))
	            val toAdd = Math.abs(rgbVal.red - curRGB.red) + 
	            	Math.abs(rgbVal.blue - curRGB.blue) + 
	            	Math.abs(rgbVal.green - curRGB.green)
	            //modify return value
	            (prevTot + toAdd, prevNum + 1)
	          }
      	}
      //set to average
      toReturn(y)(x) = (sum / tot / (255 * 3))
    } 
    new EnergyMap(toReturn)
  }

  /**
   * sets color from black to white based on energy
   * 
   * @param num		the number to convert 
   * @return 		the color
   */
  def getEnergyColor(num : Double) : Int = {
    val colorVal = (num * 255).toInt
    Utils.getIntFromRGB(colorVal, colorVal, colorVal);
  }
  
  /**
   * gets image based on energy
   * 
   * @return 	the image to return
   */
  def getImage() : BufferedImage = {
    val emap = getEnergyMap()
    val newImage = new BufferedImage(emap.getWidth(), emap.getHeight(), BufferedImage.TYPE_3BYTE_BGR)
    for (x <- 0 to (emap.getWidth() - 1); y <- 0 to (emap.getHeight() - 1)) {
      newImage.setRGB(x, y, getEnergyColor(emap.getEnergy(x, y)));
    }
    newImage
  }
  
/**
 * returns the Files that point to the animation for determining energy
 *  
 * @return		the files for animation
 */
  def getAnimPics() = {
	  Array.ofDim[File](0)
  }
}